#include "u8g2.h"
#include "u8g2Port.h"
#include "env.h"
#include "stdlib.h"
#include "def.h"

#include "u8g2PageInit.h"
#include "u8g2PageProtocolShow.h"
#include "u8g2PageMain.h"
#include "u8g2ErrShow.h"
typedef enum
{
	E_STATUS_INIT = 0,
	E_STATUS_PROTOCOL_SHOW,
	E_STATUS_INFO_SHOW,
	E_STATUS_WARN_SHOW,
	E_STATUS_ERR_SHOW,
} UI_STATUS_ENUM;

u8g2_t u8g2;

U8g2PageMainParms disp =
	{
		.batteryCurrent = 0.0,
		.batteryTemperature = 0.0,
		.batteryVoltage = 0.0,
		.chargeStatus = E_U8G2_CHARGE_STATUS_NOT_IN_CHARGE,
		.totalChargedmAH = 0,
};
void sUIServiceInit(void)
{
	u8x8PortInit();
	u8g2_Setup_ssd1312_i2c_128x64_noname_1(&u8g2, U8G2_R0, u8x8_byte_i2c, u8x8_gpio_and_delay);
	u8g2_InitDisplay(&u8g2);
	u8g2_SetPowerSave(&u8g2, 0);
	u8g2_ClearDisplay(&u8g2);
	u8g2_SetFont(&u8g2, u8g2_font_spleen16x32_mu);
	u8g2_DrawStr(&u8g2, 16, 36, "SPARKY");
	u8g2_SendBuffer(&u8g2);
}

static UI_STATUS_ENUM uiStatus = E_STATUS_INIT;
void sUILoop(void)
{
	if (env.ready == E_SUPPLY_NOT_READY && env.error != E_CRITICAL)
	{
		return;
	}
	u8g2_FirstPage(&u8g2);
	do
	{
		if(env.error == E_CRITICAL)
		{
			u8g2ErrShow(&u8g2);
			continue;
		}
		switch (uiStatus)
		{
		case E_STATUS_INIT:
		{
			if (u8g2PageInit(&u8g2))
			{
				u8g2_ClearDisplay(&u8g2); // 页面切换前请主动清理屏幕
				uiStatus = E_STATUS_PROTOCOL_SHOW;
			}
			break;
		}
		case E_STATUS_PROTOCOL_SHOW:
			if (u8G2ProtoclShow(&u8g2))
			{
				uiStatus = E_STATUS_INFO_SHOW;
			}
			break;
		case E_STATUS_INFO_SHOW:
			u8g2PageMain(&u8g2, &disp);
			break;
		case E_STATUS_WARN_SHOW:
			break;
		case E_STATUS_ERR_SHOW:
			break;
		}

	} while (u8g2_NextPage(&u8g2));
}
